package com.idea.dsl.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.idea.dsl.config.DslProperties;
import com.idea.dsl.model.ModelRequest;
import com.idea.dsl.model.ModelResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * OpenAI客户端实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OpenAiClient implements ModelClient {
    
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    private final DslProperties dslProperties;
    
    private static final String CLIENT_TYPE = "openai";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    
    @Override
    public ModelResponse chat(ModelRequest request) {
        try {
            DslProperties.ModelConfig config = dslProperties.getModels().get(CLIENT_TYPE);
            if (config == null) {
                throw new RuntimeException("OpenAI配置未找到");
            }
            
            // 构建请求体
            String requestBody = objectMapper.writeValueAsString(request);
            log.debug("OpenAI请求: {}", requestBody);
            
            // 构建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(config.getBaseUrl() + "/chat/completions")
                    .header("Authorization", "Bearer " + config.getApiKey())
                    .header("Content-Type", "application/json")
                    .post(RequestBody.create(requestBody, JSON))
                    .build();
            
            // 发送请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    throw new RuntimeException("OpenAI请求失败: " + response.code() + " " + response.message());
                }
                
                String responseBody = response.body().string();
                log.debug("OpenAI响应: {}", responseBody);
                
                return objectMapper.readValue(responseBody, ModelResponse.class);
            }
            
        } catch (IOException e) {
            log.error("OpenAI请求异常", e);
            throw new RuntimeException("OpenAI请求异常: " + e.getMessage(), e);
        }
    }
    
    @Override
    public String getClientType() {
        return CLIENT_TYPE;
    }
    
    @Override
    public boolean isAvailable() {
        DslProperties.ModelConfig config = dslProperties.getModels().get(CLIENT_TYPE);
        return config != null && StringUtils.isNotBlank(config.getApiKey());
    }
}
